// 工具函数

// 显示消息
function showMessage(text, type = 'info') {
    const msg = document.createElement('div');
    msg.className = `message ${type}`;
    msg.textContent = text;
    document.body.appendChild(msg);

    setTimeout(() => {
        msg.style.animation = 'slideIn 0.3s reverse';
        setTimeout(() => msg.remove(), 300);
    }, 3000);
}

// 显示进度
function showProgress(show, percent = 0, text = '') {
    const modal = document.getElementById('progressModal');
    const fill = document.getElementById('progressFill');
    const textEl = document.getElementById('progressText');

    if (show) {
        modal.classList.add('show');
        fill.style.width = percent + '%';
        textEl.textContent = text;
    } else {
        modal.classList.remove('show');
    }
}

// 格式化日期
function formatDate(dateStr) {
    if (!dateStr) return '';
    const d = new Date(dateStr);
    return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
}

// 文件转ArrayBuffer
function fileToArrayBuffer(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
    });
}

// 文件转DataURL
function fileToDataURL(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

// 下载文件
function downloadFile(blob, filename) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);
}

// 文本换行处理
function wrapText(text, font, fontSize, maxWidth) {
    const chars = text.split('');
    const lines = [];
    let currentLine = '';

    for (const char of chars) {
        const testLine = currentLine + char;
        const width = font.widthOfTextAtSize(testLine, fontSize);

        if (width > maxWidth && currentLine) {
            lines.push(currentLine);
            currentLine = char;
        } else {
            currentLine = testLine;
        }
    }

    if (currentLine) lines.push(currentLine);
    return lines.length > 0 ? lines : [''];
}